package com.jims.api.v1.controller.patient;

import com.alibaba.fastjson.JSON;
import com.jims.master.common.data.Message;
import com.jims.master.common.data.StringData;
import com.jims.master.common.utils.SecurityUtil;
import com.jims.master.common.web.BaseController;
import com.jims.master.modules.base.user.entity.MasterBaseinfo;
import com.jims.master.modules.base.user.entity.MasterContactinfo;
import com.jims.master.modules.base.user.entity.MasterDoctorinfo;
import com.jims.master.modules.base.user.service.MasterBaseinfoService;
import com.jims.master.modules.base.user.service.MasterContactinfoService;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.service.UserService;
import com.jims.master.modules.sys.utils.UserUtils;
import com.jims.master.modules.sys.utils.netease.NetEaseServerAPI;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 网易即时通讯Controller
 * @author WangYQ
 * @version 2017-12-23
 */

@Controller
@RequestMapping(value = "/user")
public class MyFriendController extends BaseController {
    //将本平台账号导入到网易云通信平台
    @Autowired
    UserService userService;

    @Autowired
    private MasterBaseinfoService masterBaseinfoService;

    @Autowired
    private MasterContactinfoService masterContactinfoService;

    /**
     * @Title: RegistNeteaseImV100
     * @Description: （网易即时通讯注册）
     * @param baseinfoId
     * @return java.lang.String
     * @author WangYQ
     * @date 2017-12-23
     * @throws
     */
    @RequestMapping(value = "V100/RegistNeteaseIm",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String RegistNeteaseIm(@RequestParam(required=true) String baseinfoId) throws IOException {
        Message msg=new Message();
        StringData data=new StringData();
        User doctorUser = userService.findUserByPersonId(baseinfoId);
        // 判断是否注册
        if (doctorUser != null){
            getToken(doctorUser);
            msg.setData("网易即时通讯注册成功");
        }else {
            msg.setStatus("0");
            msg.setErrCode("414");
            msg.setErrMsg("医生信息不全,没有登录信息");
        }
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: V100myNews
     * @Description: （打开网易即时通讯聊天中心）
     * @param baseinfoId
     * @return java.lang.String
     * @author WangYQ
     * @date 2017-12-23
     * @throws
     */
    @RequestMapping(value = "V100/myNews",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String myNews(@RequestParam(required=true) String baseinfoId, HttpServletRequest request) {
        Message msg=new Message();
        User user = userService.findUserByPersonId(baseinfoId);
        String token = getToken(user);
        if (token != null) {
            //更新网易用户名片，0 代表为更新初始信息，1代表已更新
            if ("0".equals(user.getNeteaseInfoFlag())) {
                boolean flag = updateNeteaseUserInfo(user);
                if (flag) {
                    user.setNeteaseInfoFlag("1");
                    userService.updateToken(user);
                }
            }
        }
        user.setId(user.getId().substring(0,32));
        user.setToken(token);
        msg.setData(user);
        return SecurityUtil.encryptMsgData(msg);
    }
    /*
    * 获取token
    * @param  user
    * @return token
    * */
    public String getToken(User user){
        String token=null;
        String httpEntity= NetEaseServerAPI.createUser((user.getId()).substring(0,32),user.getName());
        Map<Object,Object> map= NetEaseServerAPI.toMap(httpEntity);
        boolean flag= NetEaseServerAPI.isRegistNetease(map);
//          true表示原来未注册，刚注册成功
        if(!flag){
//          已经注册的用户token是否为空，为空更新
            if(user.getToken()!=null&&!user.getToken().equals("")){
                token=user.getToken();
            }else{
                token=updateToken(user);
            }
        }else{
            token= NetEaseServerAPI.getToken(map);
            user.setToken(token);
            userService.update(user);
        }
        return token;
    }

    /*
    * 获取更新后token
    * @param  user
    * @return token
    * */
    public String updateToken(User user){
        String token=null;
        String httpstr= NetEaseServerAPI.updateUserToken((user.getId()).substring(0,32));
        Map<Object,Object> map= NetEaseServerAPI.toMap(httpstr);
        boolean flag= NetEaseServerAPI.isRegistNetease(map);
        if(flag){
            token= NetEaseServerAPI.getToken(map);
            user.setToken(token);
            userService.update(user);
        }
        return token;
    }

    /**
     * 更新用户名片
     * @param  user
     * @return boolean
     */
    public boolean updateNeteaseUserInfo(User user){
        MasterBaseinfo masterBaseinfo=masterBaseinfoService.get(user.getPersionId());
        MasterContactinfo masterContactinfo=masterContactinfoService.getContactinfoByBasId(masterBaseinfo.getId());
//		accid       [云信ID，最大长度32字节，必须保证一个APP内唯一（只允许字母、数字、半角下划线_、@、半角点以及半角-组成，不区分大小写，会统一小写处理）]
        String accid="";
//		数据库user表中id不一样长
        if(user.getId().length()<32){
            accid=user.getId();
        }else {
            accid=(user.getId()).substring(0,32);
        }
//		name        [云信ID昵称，最大长度64字节，用来PUSH推送时显示的昵称]
        String name=masterBaseinfo.getName();
//		icon        [用户icon，最大长度256字节]
        String icon=masterBaseinfo.getHeadPath();
//		sign        [用户签名，最大长度256字节]
        String sign="关注健康，关爱生命！";
//		[用户email，最大长度64字节]
        String email=masterContactinfo.getEmail();
//		birth       [用户生日，最大长度16字节]
        String birth=null;
//		mobile      [用户mobile，最大长度32字节]
        String mobile=masterContactinfo.getMobilePhone();
//		gender      [用户性别，0表示未知，1表示男，2女表示女，其它会报参数错误]
        String sex=masterBaseinfo.getSex();
        int gender=0;
        if(sex==null||"".equals(sex)){
            gender=0;
        }else{
            gender=Integer.parseInt(sex);
        }
        String httpEntity= NetEaseServerAPI.updateUserInfo(accid,name,icon,sign,email,birth,mobile,gender);
        return NetEaseServerAPI.isRegistNetease(NetEaseServerAPI.toMap(httpEntity));
    }
    /**
     * @Title: getNeteaseMessageV100
     * @Description: （医生端获取im信息）
     * @param
     * @return java.lang.String
     * @author WangYQ
     * @date 2018-02-01
     * @throws
     */
    @RequestMapping(value = "V100/getImMessage",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String getImMessage( String baseId,String toBaseId,HttpServletRequest request)
    {
        Message msg=new Message();
        User user=userService.findUserByPersonId(baseId);
//        MasterBaseinfo baseinfo=new MasterBaseinfo();
//        baseinfo.setIdCard(toIdCard);
//        MasterBaseinfo masterBaseinfo=masterBaseinfoService.getByIdCard(baseinfo);
        User toUser=userService.findUserByPersonId(toBaseId);
        String result=null;
        if(toUser==null){
            result="该患者没有登录信息";
            msg.setData(result);
            return SecurityUtil.encryptMsgData(msg);
        }
        //判断医生是否有网易信息
        String userToken=getToken(user);
        if(userToken==null){
            result="医生账号无法登录即时通讯聊天";
            msg.setData(result);
            msg.setStatus("1");
            return SecurityUtil.encryptMsgData(msg);
        }

/*
        if(user.getToken()==null){
            boolean doc=registIM(user);
            if(!doc){
                result="医生账号无法登录即时通讯聊天";
                msg.setData(result);
                msg.setStatus("1");
                return SecurityUtil.encryptMsgData(msg);
            }
        }
*/
        //判断患者是否有网易信息
        String toToken=getToken(toUser);
        if(toToken==null){
            result="患者账号无法登录即时通讯聊天";
            msg.setData(result);
            msg.setStatus("1");
            return SecurityUtil.encryptMsgData(msg);
        }
        /*if(toUser.getToken()==null){
            boolean top=registIM(toUser);
            if(!top){
                result="患者账号无法登录即时通讯聊天";
                msg.setData(result);
                msg.setStatus("1");
                return SecurityUtil.encryptMsgData(msg);
            }
        }*/
        Map map=new HashMap();
        map.put("uid",user.getId().substring(0,32));
        map.put("sdktoken",userToken);
        map.put("did",toUser.getId().substring(0,32));
        result= JSON.toJSONString(map);
        /*result =  "{'ret':'true','uid':'"+user.getId().substring(0,32)+"','sdktoken':'"+user.getToken()+"','did':'"+toUser.getId().substring(0,32)+"'}";*/
        //加上返回参数
        msg.setData(result);
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: getNeteaseMessageV100
     * @Description: （获取网易登录信息）
     * @param
     * @return java.lang.String
     * @author WangYQ
     * @date 2018-02-01
     * @throws
     */
    @RequestMapping(value = "V100/getNeteaseMessage",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String getNeteaseMessage( HttpServletRequest request,String baseId,String toBaseId)
    {
        Message msg=new Message();
        User user=userService.findUserByPersonId(baseId);
        User toUser=userService.findUserByPersonId(toBaseId);
        String result=null;
        //判断医生是否有网易信息
        String userToken=getToken(user);
        if(userToken==null){
            result="医生账号无法登录即时通讯聊天";
            msg.setData(result);
            msg.setStatus("1");
            return SecurityUtil.encryptMsgData(msg);
        }
//        if(user.getToken()==null||user.getToken()==""){
//            boolean doc=registIM(user);
//            if(!doc){
//                result="医生账号无法登录即时通讯聊天";
//                msg.setData(result);
//                msg.setStatus("1");
//                return SecurityUtil.encryptMsgData(msg);
//            }
//        }
        //判断患者是否有网易信息
       String toToken= getToken(toUser);
        if(toToken==null){
            result="患者账号无法登录即时通讯聊天";
            msg.setData(result);
            msg.setStatus("1");
            return SecurityUtil.encryptMsgData(msg);
        }
/*
        if(toUser.getToken()==null||toUser.getToken()==""){
            boolean top=registIM(toUser);
            if(!top){
                result="患者账号无法登录即时通讯聊天";
                msg.setData(result);
                msg.setStatus("1");
                return SecurityUtil.encryptMsgData(msg);
            }
        }
*/
        Map map=new HashMap();
       /* map.put("uid",user.getId().substring(0,32));
        map.put("sdktoken",user.getToken());
        map.put("did",toUser.getId().substring(0,32));*/
        NeteaseMessage nm=new NeteaseMessage();
        nm.setUid(user.getId().substring(0,32));
        nm.setSdktoken(userToken);
        nm.setDid(toUser.getId().substring(0,32));
//        nm.setSdktoken(user.getToken());
//        nm.setDid(toUser.getId().substring(0,32));
        /*result =  "{'ret':'true','uid':'"+user.getId().substring(0,32)+"','sdktoken':'"+user.getToken()+"','did':'"+toUser.getId().substring(0,32)+"'}";
        //加上返回参数*/
        msg.setData(nm);
        return SecurityUtil.encryptMsgData(msg);
    }

    /*
    * 注册网易信息
    * @param  user
    * @return token
    * */
    public boolean registIM(User user){
        String token=getToken(user);
        if(token!=null&& !token.equals("")){
            user.setToken(token);
            updateToken(user);
            MasterBaseinfo masterBaseinfo=masterBaseinfoService.get(user.getPersionId());
            MasterContactinfo masterContactinfo=masterContactinfoService.getContactinfoByBasId(user.getPersionId());
           return NetEaseServerAPI.updateNeteaseUserInfo(user,masterBaseinfo,masterContactinfo);
        }else {
            return false;
        }
    }

}
